package org.budo.dubbo.http.client.java.impl;

import org.budo.dubbo.http.client.java.RequestContext;
import org.budo.dubbo.http.client.java.Transporter;
import org.budo.dubbo.http.client.java.exception.ApiErrorException;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;

/**
 * HTTP 通信层实现
 * 
 * @author lmw
 */
public class BudoRequestTransporter implements Transporter {
    /**
     * 参数以数组传输
     */
    private static final String INVOCATION_ADAPTER = "org.budo.dubbo.protocol.http.invocation.adapter.impl.WebHttpArgumentArrayInvocationAdapter";

    public String request(RequestContext requestContext) {
        Request request = new Request();
        request.setConnectTimeout(3 * 1000);
        request.setReadTimeout(3 * 1000);
        request.setMethod(Request.POST);
        request.setContentType("application/json");
        request.setHeader("invocationAdapterType", INVOCATION_ADAPTER);

        request.setUrl(requestContext.getUrl() + "/" + requestContext.getInterfaceType() + "." + requestContext.getMethodName());

        request.setHeaders((requestContext.getHeaders()));
        request.setParameters((requestContext.getParameters()));
        request.setRequestBody(requestContext.getRequestBody());

        Response response = request.execute();
        if (response.getStatus().equals(200)) {
            return response.getBody();
        } else {
            throw new ApiErrorException("response=" + (null == response ? response : response.toSimpleString()));
        }
    }
}